//
//  UICollectionViewCell+MKUICollectionViewCellProtocol.m
//  MKUI
//
//  Created by sushangjin on 14/12/29.
//  Copyright © 2020 sushangjin. All rights reserved.
//

#import "UICollectionViewCell+MKUICollectionViewCellProtocol.h"
#import "UIScrollView+MKUI.h"
#import "MKUICollectionViewCellModel.h"
#import "UICollectionViewFlowLayout+MKUI.h"
#import <objc/runtime.h>

@implementation UICollectionViewCell (MKUICollectionViewCellProtocol)
#pragma mark - deleagte:MKUICollectionViewCellProtocol
- (MKUICollectionViewCellModel *)collectionCellModel{
	MKUICollectionViewCellModel *cellModel = objc_getAssociatedObject( self, "UICollectionViewCell.MKUICollectionViewCellModel.collectionCellModel");
	return cellModel;
}
- (void)setCollectionCellModel:(MKUICollectionViewCellModel *)collectionCellModel{
	objc_setAssociatedObject( self, "UICollectionViewCell.MKUICollectionViewCellModel.collectionCellModel", collectionCellModel, OBJC_ASSOCIATION_RETAIN_NONATOMIC );
}
+ (CGSize)dynamicSizeWithCollectionView:(UICollectionView *)collectionView collectionCellModel:(MKUICollectionViewCellModel *)collectionCellModel cellShareInstance:(UICollectionViewCell<MKUICollectionViewCellProtocol> *)cell calBlock:(CGSize(^)(UICollectionView *collectionView,MKUICollectionViewCellModel *cellModel,id cell))block{
    
	CGSize size = CGSizeZero;
    CGRect bounds = collectionView.mk_contentBounds;
    
    CGRect originBounds = cell.bounds;
    
    UICollectionViewFlowLayout *flowlayout = collectionView.mk_collectionViewFlowLayout;
    UIEdgeInsets sectionInsets = UIEdgeInsetsZero;
    if(flowlayout){
        NSInteger sectionIndex = collectionCellModel.indexPathInModel.section;
        sectionInsets = [flowlayout mk_insetForSectionAtIndex:sectionIndex];
        bounds = UIEdgeInsetsInsetRect(bounds, sectionInsets);
    }

    bounds.origin = CGPointZero;
    cell.bounds = bounds;
    cell.collectionCellModel = collectionCellModel;
    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    if(block){
        size = block(collectionView,collectionCellModel,cell);
    }
    cell.collectionCellModel = nil;
    cell.bounds = originBounds;

    //限制itemSize不能超过cell可布局区域的范围
    if(flowlayout){
        if(flowlayout.scrollDirection==UICollectionViewScrollDirectionVertical){
            size.width = MIN(size.width,bounds.size.width);
        }else{
            size.height = MIN(size.height,bounds.size.height);
        }
    }
    
    //消除浮点误差
    size.width = ceil(size.width);
    size.height = ceil(size.height);
	return size;
}
@end
